package com.rgsx.utils;

import com.rgsx.data.DataPool;
import io.jsonwebtoken.*;

import java.util.Date;

public class JWTUtil {
    private static String signature = "yng666";//令牌
    private static long time = 1000 * 60 * DataPool.tokenAndRedis_login_TimeOut;//过期时间

    public static boolean verify(String token){
        try {
            JwtParser jwtParser = Jwts.parser();
            Jws<Claims> claimsJws = jwtParser
                    .setSigningKey(signature).parseClaimsJws(token);

            Claims body = claimsJws.getBody();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static long getUserId(String token){
        try {
            JwtParser jwtParser = Jwts.parser();
            Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);

            Claims body = claimsJws.getBody();

            return (long) body.get("id");
        } catch (Exception e) {
            return -1;
        }
    }

    public static String getToken(long id){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //头信息
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("id",id)
                .setSubject("admin")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(String.valueOf(id))
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();

        return jwtToken;
    }

}
